package com.example.yibu.yibService;

import com.alibaba.fastjson.JSONObject;
import com.example.yibu.modelConfig.HashMapConfig;
import com.example.yibu.modelConfig.QueueEntity;
import com.example.yibu.modelConfig.pool.LimitedThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.*;

@Slf4j
@Service
public class AiTestVService {
    @Autowired
    private HashMapConfig hashMapConfig;
    private static final ThreadPoolExecutor POOL_EXECUTOR = LimitedThreadPool.createPool();

    @Async("serviceTask")
    public void startTask(QueueEntity queueTask, Runnable callback) {
        try {
            JSONObject jsonObject = JSONObject.parseObject((String) queueTask.getRequestDate());
            //业务代码
            System.out.println("业务代码");
        }catch (Exception e) {
            log.error("任务处理过程中发生未知错误: {}", e.getMessage());
        } finally {
            if (callback != null) {
                callback.run();
            }
        }

    }

    public String getTaskResult(String id) {
        // 获取处理结果
        String object = "";
        while (true){
            object = String.valueOf(hashMapConfig.getHashMap(id, "任务进行中"));
            if ("进行中".equals(object)){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }else {
                break;
            }
        }
        hashMapConfig.removeHashMap(id);
        return object;
    }

    /*

      public List<AipaperContentVo> generateContentAsync(String title, List<AiPaperFocusVo> focus, String educational,Integer wordsNumber, HttpServletResponse res) {
        // 创建异步任务
        List<CompletableFuture<AipaperContentVo>> futures = new ArrayList<>();
        for (AiPaperFocusVo focu : focus) {
            CompletableFuture<AipaperContentVo> future = CompletableFuture.supplyAsync(() -> {
                try {
                    // 生成内容
                    return this.creatorContent(title, focu.getFocu(), focu.getDescription(), educational,wordsNumber, res);
                } catch (Exception e) {
                    log.error("无法生成论文内容 " + focu.getFocu() + ": " + e.getMessage(), e);
                    return new AipaperContentVo(); // 返回一个默认值或处理错误逻辑
                }
            }, POOL_EXECUTOR);
            futures.add(future);
        }
        try {
            // 等待所有异步任务完成并获取结果
            CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
            return allOf.thenApply(v -> futures.stream()
                            .map(CompletableFuture::join) // 获取每个任务的结果
                            .collect(Collectors.toList())) // 收集结果到列表
                    .get(180, TimeUnit.SECONDS); // 设置超时时间
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            log.error("异步调用发生异常：", e);
            Thread.currentThread().interrupt(); // 保证线程中断状态
            throw new RuntimeException("异步调用失败", e);
        }
    }

     */


}
